# 第一阶段：依赖安装和构建
FROM python:3.12-slim as builder

# 设置构建参数
ARG POETRY_VERSION=2.1.3
ARG PYTHON_INTERPRETER=/usr/local/bin/python3.12

# 设置工作目录
WORKDIR /app

# 安装必要的系统依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends libgomp1 && \
    rm -rf /var/lib/apt/lists/*

# 验证Python解释器
RUN ${PYTHON_INTERPRETER} --version && \
    ls -la /usr/local/bin/python*

# 安装 Poetry
RUN ${PYTHON_INTERPRETER} -m pip install --upgrade pip && \
    ${PYTHON_INTERPRETER} -m pip install poetry==${POETRY_VERSION}

# 复制 Poetry 文件
COPY pyproject.toml poetry.lock ./

# 使用 Poetry 安装生产环境依赖
RUN ${PYTHON_INTERPRETER} -m poetry config virtualenvs.create false && \
    ${PYTHON_INTERPRETER} -m poetry install --no-interaction --no-ansi --no-root

# 复制应用代码
COPY ./src ./src
COPY ./.env ./.env


# 第二阶段：运行时环境
FROM python:3.12-slim

# 设置Python解释器
ENV PYTHON_INTERPRETER=/usr/local/bin/python3.12

# 设置工作目录
WORKDIR /app

# 从构建阶段复制整个Python环境
COPY --from=builder /usr/local/lib/python3.12/site-packages/ /usr/local/lib/python3.12/site-packages/
COPY --from=builder /usr/local/bin/ /usr/local/bin/

# 复制应用代码
COPY --from=builder /app /app


# 暴露端口
EXPOSE 5000

# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV FLASK_APP=src.run:app
ENV FLASK_ENV=production

# 启动命令
CMD ["/usr/local/bin/python3.12", "-m", "flask", "run", "--host=0.0.0.0"]
